package com.juzipi.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.juzipi.data.model.Teacher;
import com.juzipi.data.model.TeacherAge;
import com.juzipi.data.service.TeacherAgeService;
import com.juzipi.data.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author juzipi
 * @Date 2021/6/30 15:28
 * @Info
 */
@RestController
public class TeacherController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private TeacherAgeService teacherAgeService;


    public static final Random random = new Random();

    String familyName1 = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻水云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳鲍史唐费岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅卞齐康伍余元卜顾孟平"
            + "黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计成戴宋茅庞熊纪舒屈项祝董粱杜阮席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田胡凌霍万柯卢莫房缪干解应宗丁宣邓郁单杭洪包诸左石崔吉"
            + "龚程邢滑裴陆荣翁荀羊甄家封芮储靳邴松井富乌焦巴弓牧隗山谷车侯伊宁仇祖武符刘景詹束龙叶幸司韶黎乔苍双闻莘劳逄姬冉宰桂牛寿通边燕冀尚农温庄晏瞿茹习鱼容向古戈终居衡步都耿满弘国文东殴沃曾关红游盖益桓公晋楚闫";
    String familyName2 = "欧阳太史端木上官司马东方独孤南宫万俟闻人夏侯诸葛尉迟公羊赫连澹台皇甫宗政濮阳公冶太叔申屠公孙慕容仲孙钟离长孙宇文司徒鲜于司空闾丘子车亓官司寇巫马公西颛孙壤驷公良漆雕乐正宰父谷梁拓跋夹谷轩辕令狐段干百里呼延东郭南门羊舌微生公户公玉公仪梁丘公仲公上公门公山公坚左丘公伯西门公祖第五公乘贯丘公皙南荣东里东宫仲长子书子桑即墨达奚褚师吴铭";
    String girlName = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽";
    String boyName = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";


    public static int limit = 900;
    public static int offset = 9411300;


    @GetMapping("get")
    public Teacher get() {
        return teacherService.getTeacherById(1L);
    }

    @DeleteMapping("del")
    public String del() {
        for (int i = 0; i < 100; i++) {
            teacherService.delete();
        }
        return "删除中";
    }


    @DeleteMapping("delage")
    public String delage() {
        for (int i = 0; i < 20; i++) {
            teacherAgeService.delete();
        }
        return "删除中";
    }


    @GetMapping("name")
    public Teacher getName(@RequestParam String name) {
        long start = System.currentTimeMillis();
        Teacher one = teacherService.getOne(new QueryWrapper<Teacher>().lambda().eq(Teacher::getName, name));
        long end = System.currentTimeMillis();
        double l1 = (double) end - start;
        double l = l1 / 1000;
        System.out.println("未建立索引: " + l + "秒");
        return one;
    }


    @GetMapping("insert")
    public String insertData() {
        long start = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        for (int i = 0; i < 2000; i++) {
            ArrayList<Teacher> teachers = new ArrayList<>();
            for (int j = 0; j < 400; j++) {
                Teacher teacher = new Teacher();
                teacher.setId(null);
                //炸裂，随机数有问题
                teacher.setAge((int) (10 + (Math.random()) * (60 - 10)));
                String[] nameAndSex = getNameAndSex(getGender());
                String name = nameAndSex[0];
                String gender = nameAndSex[1];
                teacher.setGender(gender);
                teacher.setName(getFamilyName().concat(name));
                Date parse = null;
                try {
                    parse = simpleDateFormat.parse(simpleDateFormat.format(System.currentTimeMillis()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                teacher.setCreateTime(parse);
                teachers.add(teacher);
            }
            teacherService.saveBatch(teachers);
        }
        long end = System.currentTimeMillis();
        double x = (double) end - start;
        System.out.println(x / 1000 + "秒");
        return x / 1000 + "秒";
    }

    @GetMapping("update")
    public String update() {
        //想到另一个思路了,查500添加500重复n次
        //越来越慢
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            List<Long> list = teacherService.selectLimit(limit, offset);//Integer limit,Integer offset
            //为什么会报重复,第三轮就报错了，奇怪,pass了
            System.out.println(offset += 900);//offset表示是执行开始的位置
            System.out.println(limit);//limit表示是条数
            //遍历出这90w数据，问题：如果再给里面套循环他会是重复的450条值（因为只遍历了一次），循环套外面就会遍历n次这90w数据
            ArrayList<TeacherAge> objects = new ArrayList<>();
            for (Long tea : list) {//一次900
                //准备600条数据
                //如果上面加循环，这里值就是固定循环一个了，不行
                //这里不应该再加循环，不然就是一直循环一个值
                TeacherAge teacherAge = new TeacherAge();
                teacherAge.setId(tea);
                teacherAge.setNum((int) (10 + (Math.random()) * (60 - 10)));
                objects.add(teacherAge);
                //一次添加
//                teacherAgeService.saveBatch(objects);
//                (int) (10 + (Math.random()) * (60 - 10))

            }
            teacherAgeService.saveBatch(objects);

        }

        long end = System.currentTimeMillis();
        System.out.println((double) (end - start) / 1000+"秒");
        return "成功";

    }


    @GetMapping("age")
    public void addAge() {
//        for (int i = 0; i < 15000; i++) {
//            ArrayList<TeacherAge> objects = new ArrayList<>();
//            for (int j = 0; j < 800; j++) {
//                TeacherAge teacherAge = new TeacherAge();
//                teacherAge.setNum((int) (10 + (Math.random()) * (60 - 10)));
//                objects.add(teacherAge);
//            }
//        int limit = 800;
//        int offset = 0;
        for (int i = 0; i < 100; i++) {
            //600, 0
            List<Long> longs = teacherAgeService.selectLimit(limit, offset);
            ArrayList<Integer> integers = new ArrayList<>();
            for (int j = 0; j < 600; j++) {
                int i1 = (int) (10 + (Math.random()) * (60 - 10));
                integers.add(i1);
            }
            teacherAgeService.updateAll(longs, integers);
            offset += 600;
        }

//            teacherAgeService.saveOrUpdateBatch(objects);
//        }
    }


    //不好用
//    @GetMapping("update")
//    public Boolean update(){
//        return teacherService.update(new UpdateWrapper<Teacher>().lambda().eq(Teacher::getAge, 900).set(Teacher::getAge, (int) (10 + (Math.random()) * (60 - 10))));
//    }


    public static String getChineseRandomNickname(int length) {
        StringBuilder randomName = new StringBuilder();
        for (int i = 0; i < length; i++) {
            String str = null;
            int hightPos, lowPos; // 定义高低位
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
            byte[] b = new byte[2];
            b[0] = (Integer.valueOf(hightPos).byteValue());
            b[1] = (Integer.valueOf(lowPos).byteValue());
            try {
                str = new String(b, "GBK"); // 转成中文
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            randomName.append(str);
        }
        return randomName.toString();
    }

    public static String getGender() {
        int i = random.nextInt(2) + 1;
        return i == 1 ? "男" : "女";
    }

    public String getFamilyName() {
        String str = "";
        int randNum = new Random().nextInt(2) + 1;
        int strLen = randNum == 1 ? familyName1.length() : familyName2.length();
        int index = new Random().nextInt(strLen);
        if (randNum == 1) {
            str = String.valueOf(familyName1.charAt(index));
        } else {
            str = (index & 1) == 0 ? familyName2.substring(index, index + 2) :
                    familyName2.substring(index - 1, index + 1);
        }
        return str;
    }

    public String[] getNameAndSex(String sex) {
        String[] nameSex = new String[2];
        int randNum = new Random().nextInt(2) + 1;
        int strLen = sex.equals("男") ? boyName.length() : girlName.length();
        int index = (randNum & 1) == 0 ? new Random().nextInt(strLen - 1) :
                new Random().nextInt(strLen);
        nameSex[0] = sex.equals("男") ? boyName.substring(index, index + randNum) :
                girlName.substring(index, index + randNum);
        nameSex[1] = sex.equals("男") ? "男" : "女";
        return nameSex;
    }

    public static int getAge() {
        return random.nextInt(4) + 18;
    }


}
